package com.minelx.statementsplus.cha.base;

import java.util.function.Supplier;

public class RetryingExecutor<R> {
	// FIXME 2022/4/13 wait for fixing.     move it to MineLXUtilities
	// FIXME 2022/4/9 wait for fixing.     orElseThrow orElse
	R get(Supplier<R> supplier, int retryingCounts, Class<?> interceptedException) {
		try {
			return supplier.get();
		} catch (Exception e) {
			if (!(e.getClass().equals(interceptedException))) {
				throw new RuntimeException("error while cached an unexpected exception while get object.", e);
			}
			// occurred exception while parsing response json text
			System.err.println("occurred exception while fetching object from supplier.");
			if (retryingCounts == 0) {
				throw new IllegalStateException("can't retrying anymore.");
			}
			// have a lil rest for the next trying
			try {
				Thread.sleep(HttpResponseFetcher.REST_MILLIS_BEFORE_RETRYING);
			} catch (InterruptedException ex) {
				throw new RuntimeException("error while waiting for next time of retrying.", ex);
			}
			// recursively get
			return get(supplier, retryingCounts - 1, interceptedException);
		}
	}

	static <R> R retryingGet(Supplier<R> whom, int retryingCount, Class<?> interceptedException) {
		return new RetryingExecutor<R>().get(whom, retryingCount, interceptedException);
	}
}
